package com.schoolai.schoolset.auth.filter;

import com.nimbusds.jose.JOSEException;
import com.schoolai.schoolset.auth.service.JwtTokenProvider;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.text.ParseException;

/**
 * Copyright(C),2019-2025，XX公司
 * FileName:JwtAuthenticationFilter
 * Author:bobby
 * 创建时间：2025/10/21 16:38
 * Description:token鉴权
 * History:
 * <auth>        <time>       <version>       <desc>
 * 作者          修改时间       版本号         描述
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    private final JwtTokenProvider jwtTokenProvider;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 从请求中获取 token，这里假设 token 在 header 中，键名为 "Authorization"
        String token = request.getHeader("Authorization");
        // System.out.println("token:"+token);
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 去除 "Bearer " 前缀
            // 这里可以调用一个服务来验证和解析 token，例如 JwtTokenUtils.validateAndParseToken(token)
            Authentication authentication = null; // 假设你有一个服务来处理 token
            try {
                authentication = jwtTokenProvider.getAuthentication(token);
            } catch (GeneralSecurityException e) {
                throw new RuntimeException(e);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            } catch (JOSEException e) {
                throw new RuntimeException(e);
            }
            if(authentication != null) {
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        filterChain.doFilter(request, response);
    }
}
